<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="上次执行" prop="lastExecResult">
        <el-select v-model="queryParams.lastExecResult" placeholder="请选择执行状态" clearable size="small">
           <el-option
            v-for="dict in resultOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="源数据源连接名称" prop="sourceName">
        <el-input
          v-model="queryParams.sourceName"
          placeholder="请输入源数据源连接名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="0 不需要Java，1需要Java代码" prop="isNeedJava">
        <el-input
          v-model="queryParams.isNeedJava"
          placeholder="请输入0 不需要Java，1需要Java代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="目标数据源连接名称" prop="targetName">
        <el-input
          v-model="queryParams.targetName"
          placeholder="请输入目标数据源连接名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目标表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入目标表名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:trans:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['data:trans:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['data:trans:remove']"
        >删除</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:trans:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:trans:export']"
        >导出</el-button>
      </el-col>-->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="left" prop="taskName" />
      <el-table-column label="任务描述" align="left" prop="taskDesc" />
      <el-table-column label="任务周期" align="center" prop="cronExpression" />
      <el-table-column label="定时任务开关" align="center">
          <template slot-scope="scope">
          <el-switch
            v-model="scope.row.taskStatus"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="上次转换完成时间" align="center" prop="lastExecTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastExecTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="转换状态" align="center" prop="lastExecResult" :formatter="resultFormat"/> -->
      <el-table-column label="转换状态" align="center" prop="lastExecResult">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_trans_result" :value="scope.row.lastExecResult"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row, 'view')"
            v-hasPermi="['system:trans:edit']"
          >查看</el-button>
        <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleRun(scope.row)"
            v-hasPermi="['system:trans:edit']"
          >运行一次</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:trans:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:trans:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据转换任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="510px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDesc">
          <el-input v-model="form.taskDesc" placeholder="请输入任务描述" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="任务周期" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="请输入时间表达式" :disabled="!isEdit"/>

        </el-form-item>
        <el-form-item label="源连接" prop="sourceId">
            <el-select v-model="form.sourceId" placeholder="请选择源连接" clearable size="small" :disabled="!isEdit">

                <el-option v-for="item in druidOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="目标连接" prop="targetId">
            <el-select v-model="form.targetId" placeholder="请选择目标连接" clearable size="small" :disabled="!isEdit">
                <el-option v-for="item in druidOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="输出模式" prop="outputType">
            <el-select v-model="form.outputType" placeholder="请选择输出模式" clearable size="small" :disabled="!isEdit">
                <el-option v-for="item in outputOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
        </el-form-item>
        <el-form-item label="源表SQL" prop="tableInputSql">
          <el-input v-model="form.tableInputSql" type="textarea" placeholder="请输入内容" :disabled="!isEdit"/>
        </el-form-item>
        <!-- <el-form-item prop="isNeedJava">
          <el-checkbox v-model="form.isNeedJava" label="是否调用Java" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="Java代码" prop="javaCode" v-if="form.isNeedJava != '0'">
          <el-input v-model="form.javaCode" type="textarea" placeholder="请输入Java代码" :disabled="!isEdit"/>
        </el-form-item> -->
        <el-form-item label="目标表名" prop="tableName">
          <el-input v-model="form.tableName" placeholder="请输入目标表名" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="源表主键" prop="lookupKey" v-if="form.outputType != '0'">
          <el-input v-model="form.lookupKey" placeholder="请输入源数据主键" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="关联标识符" prop="conditionKey" v-if="form.outputType != '0'">
          <el-input v-model="form.conditionKey" placeholder="请输入关联标识符" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="目标表主键" prop="streamKey" v-if="form.outputType != '0'">
          <el-input v-model="form.streamKey" placeholder="请输入目标数据主键" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="源数据列" prop="lookupColums">
          <el-input v-model="form.lookupColums" type="textarea" placeholder="请输入列名，用逗号隔开" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="目标数据列" prop="streamColums">
          <el-input v-model="form.streamColums" type="textarea" placeholder="请输入列名，用逗号隔开" :disabled="!isEdit"/>
        </el-form-item>
        <el-form-item label="例外数据列" prop="exceptionColums">
          <el-input v-model="form.exceptionColums" type="textarea" placeholder="请输入列名，用逗号隔开" :disabled="!isEdit"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isEdit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!--        <div class="el-upload__tip" slot="tip">
                  <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
                </div>-->
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrans, getTrans, delTrans, addTrans, updateTrans, exportTrans, runTrans, changeTrans } from "@/api/data/trans";
import { listAllDruid } from "@/api/data/druid";
import {getToken} from "@/utils/auth";
import { Alert } from "element-ui";

export default {
  name: "Trans",
  dicts: ['sys_trans_result'],
  data() {
    return {
      isEdit: false, // 修改模态框的确定按钮是否显示
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据转换任务表格数据
      transList: [],
      // 连接选项
      druidOptions: [],
      // 输出模式选项
      outputOptions: [],
      // 任务状态数据字典
      statusOptions: [],
      // 任务状态数据字典
      resultOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/trans/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        taskDesc: null,
        taskStatus: null,
        cronExpression: null,
        lastExecTime: null,
        lastExecResult: null,
        sourceId: null,
        sourceName: null,
        tableInputSql: null,
        isNeedJava: null,
        javaCode: null,
        targetId: null,
        targetName: null,
        tableName: null,
        lookupKey: null,
        conditionKey: null,
        streamKey: null,
        lookupColums: null,
        streamColums: null,
        updateUser: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        cronExpression: [
          { required: true, message: "时间表达式不能为空", trigger: "blur" }
        ],
        sourceId: [
          { required: true, message: "源数据源连接id不能为空", trigger: "blur" }
        ],
        sourceName: [
          { required: true, message: "源数据源连接名称不能为空", trigger: "blur" }
        ],
        outputType: [
          { required: true, message: "请选择输出模式", trigger: "blur" }
        ],
        tableInputSql: [
          { required: true, message: "表输入SQL不能为空", trigger: "blur" }
        ],
        targetId: [
          { required: true, message: "目标数据源连接id不能为空", trigger: "blur" }
        ],
        targetName: [
          { required: true, message: "目标数据源连接名称不能为空", trigger: "blur" }
        ],
        tableName: [
          { required: true, message: "目标表名不能为空", trigger: "blur" }
        ],
        lookupKey: [
          { required: true, message: "源数据集合主键不能为空", trigger: "blur" }
        ],
        conditionKey: [
          { required: true, message: "关联标识符不能为空", trigger: "blur" }
        ],
        streamKey: [
          { required: true, message: "目标数据集合主键不能为空", trigger: "blur" }
        ],
        lookupColums: [
          { required: true, message: "源数据集合列名，按顺序以逗号隔开不能为空", trigger: "blur" }
        ],
        streamColums: [
          { required: true, message: "目标数据集合列名，按顺序以逗号隔开不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_trans_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_trans_result").then(response => {
      this.resultOptions = response.data;
    });
    this.getDicts("sys_output_type").then(response => {
      this.outputOptions = response.data;
    });
  },
  methods: {
    /** 查询数据转换任务列表 */
    getList() {
      this.loading = true;
      listTrans(this.queryParams).then(response => {
        this.transList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskDesc: null,
        taskStatus: "0",
        cronExpression: "0 15 10 * * ?",
        lastExecTime: null,
        lastExecResult: null,
        sourceId: null,
        sourceName: null,
        tableInputSql: null,
        isNeedJava: null,
        javaCode: null,
        targetId: null,
        targetName: null,
        tableName: null,
        lookupKey: null,
        conditionKey: null,
        streamKey: null,
        lookupColums: null,
        streamColums: null,
        createTime: null,
        updateUser: null,
        updateTime: null,
        outputType: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isEdit = true;
      this.reset();
      this.open = true;
      this.title = "添加数据转换任务";
      listAllDruid().then(response => {
        this.druidOptions = response;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isEdit = !(arguments[1] === 'view');
      this.reset();
      const id = row.id || this.ids
      getTrans(id).then(response => {
        this.form = response.data
        if (JSON.stringify(this.isEdit)) {
          if (this.form.taskStatus === '1') {
            this.$message.error('启用状态的任务不能修改')
            return
          }
          this.title = '修改数据转换任务'
        } else {
          this.title = '查看数据转换任务'
        }
        this.open = true
      });
      listAllDruid().then(response => {
        this.druidOptions = response
      })
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.isEdit) {
        this.$message.error('启用没在编辑状态，不能修改')
        return
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTrans(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addTrans(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      if (row.taskStatus == '1') {
          this.$message.error('启用状态的任务不能删除');
          return;
      }
      this.$confirm('是否确认删除此转换任务?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTrans(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(function() {});
    },
      /** 运行一次按钮操作 */
    handleRun(row) {
      let _this = this;
      const ids = row.id || _this.ids;
      _this.$confirm('是否确认运行此转换任务?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          runTrans(ids).then(response => {
            if (response.code === 200) {
              _this.getList();
              _this.$modal.msgSuccess("运行成功");
            }
          });
        }).catch(function() {});
    },
     // 任务状态修改
    handleStatusChange(row) {
      let _this = this;
      let text = row.taskStatus === "0" ? "停用" : "启用";
      this.$confirm('确认要"' + text + '""' + row.taskName + '"任务吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          changeTrans(row.id, row.taskStatus).then(response => {
            if (response.code === 200) {
              _this.$modal.msgSuccess(text + "成功");
            }
          });
        }).catch(function() {
          row.taskStatus = row.taskStatus === "0" ? "1" : "0";
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有转换任务?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportTrans(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
     // 任务状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.taskStatus);
    },
     // 任务状态字典翻译
    resultFormat(row, column) {
      return this.selectDictLabel(this.resultOptions, row.lastExecResult);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
